package day15.edu;
// Created: 15/09/2025, ChangJiang Ru
public class ProducerConsumerTest {
    public static void main(String[] args)
    {
        Clerk clerk = new Clerk();

        Producer producer1 = new Producer(clerk);
        Consumer consumer1 = new Consumer(clerk);

        producer1.setName("The producer 1");
        consumer1.setName("The consumer 1");

        producer1.start();
        consumer1.start();
    }
}

class Producer extends Thread{
    private Clerk clerk;

    public Producer(Clerk clerk)
    {
        this.clerk = clerk;
    }

    @Override
    public void run()
    {
        System.out.println("The producer is working ...");
        try
        {
        Thread.sleep(1000);
        }catch(InterruptedException e)
        {
            e.printStackTrace();
        }
        clerk.addProduct();
    }
}

class Consumer extends Thread{
    private Clerk clerk;

    public Consumer(Clerk clerk)
    {
        this.clerk = clerk;
    }

    @Override
    public void run()
    {
        System.out.println("The consumer is consuming ...");
        try
        {
        Thread.sleep(1000);
        }catch(InterruptedException e)
        {
            e.printStackTrace();
        }

        clerk.minusProduct();
    }
}

class Clerk{
    private int productNumber = 0;

    // Create method to add the product of number
    public synchronized void addProduct()
    {
        while(true) {


            if (productNumber >= 20) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            productNumber++;
            System.out.println(Thread.currentThread().getName() + " have the product is : " + productNumber);

            notify();
        }
    }

    // Create method to minus the product of number
    public synchronized void minusProduct()
    {
        while(true) {


            if (productNumber <= 0) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println(Thread.currentThread().getName() + " have the product is : " + productNumber);
            productNumber--;
            notify();
        }
    }
}